import { login, userInfo, userPhoto } from '@/api/user'
import { getToken, setToken, removeToken, setTimeStamp } from '@/utils/auth'

const state = {
    //将获取到的token,放在state里面
    token: getToken(),
    //保存用户信息
    userInfo: {},
}


const mutations = {
    //通过actions获取到的token,保存到vuex中
    setToken: (state, token) => {
        state.token = token
            //存储到本地
        setToken(token)
    },
    //获取用户信息
    setUserInfo: (state, payload) => {
        state.userInfo = payload
    },

    //删除token
    reomveToken: (state) => {
        state.token = null
            //删除本地token
        removeToken()
    },
    removeUserInfo: (state) => {
        state.userInfo = {}
    }
}


const actions = {
    async login(context, data) {
        try {
            let res = await login(data);
            context.commit('setToken', res.data)
                //在cookes存入时间戳
            setTimeStamp()
        } catch (error) {
            // 来到这证明请求失败，让代码报错
            // 这样子Login.vue就能收到失败的信息了
            return Promise.reject(error)
        }
        // console.log(res);
    },
    async getUserInfo(context) {
        let res = await userInfo();
        let res1 = await userPhoto(res.data.userId)
            // console.log(res);
        let allInfo = {
            ...res.data,
            ...res1.data
        }
        console.log(allInfo);
        context.commit('setUserInfo', allInfo)
    },
    //退出登录,清除token和用户信息
    //使用解构赋值
    logout({ commit }) {
        //清除token
        commit('reomveToken')
            //清除用户信息
        commit('removeUserInfo')
            //清除路由
        resetRouter()

    }
}
export default {
    namespaced: true,
    state,
    mutations,
    actions
}